package demo.helper;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;

/**
Los tildes en los comentarios son omitidos intencionalmente
 * 
 * @author 
 * <p>Title: cl.presto.redhat.srpa.esb.helpers.connects.WSHTTPClientHelper.java</p>
 * <p>Description:       </p>
 * <p>Copyright: Copyright (c) 30-08-2010 </p>
 * <p>Company: RED HAT  </p>
 * 
 * version 1.0
 */
public class WSHTTPClientHelper {
	
	protected HttpClient httpClient;
	protected PostMethod postMethod;
	
	public WSHTTPClientHelper(String locationWS) {
		
		postMethod = new PostMethod(locationWS);
	}
	

	/**
	 * @param soap
	 * @param timeOut
	 * @param soapAction
	 * @throws IOException 
	 */
	public void executeMethod(String soap, int timeOut, String soapAction) throws IOException  {
		
		
		httpClient = new HttpClient();
		//time out para la conexion y para la respuesta de datos
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeOut);
		httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeOut);
				
		StringRequestEntity	requestEntity = new StringRequestEntity(soap);
		postMethod.setRequestHeader("SOAPAction",soapAction);
		postMethod.setRequestEntity(requestEntity);

		try {
			//se invoca el WS
				httpClient.executeMethod(postMethod);
		} catch (HttpException e) {
				throw e;
		} catch (IOException e) {
				throw e;
		}		
		
	}
	
	
	/**
	 * @return
	 * @throws IOException 
	 * @throws IOException
	 */
	public String getResponseBody() throws IOException{
		
		String response;
		try {			
			//se obtiene la respuesta WS
			response = postMethod.getResponseBodyAsString();
			System.out.println("Respuesta WS "+response);
		} catch (IOException e) {
			throw e;
		}
		finally{
			postMethod.releaseConnection();
		}	
				
		return response;
	}
	

	
}
